﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMSGSC.Common;
using DevExpress.XtraEditors;
using PMSGSC.DAL;
using PMSGSC.BLL;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Controls;
using System.Globalization;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data.Linq;
using DevExpress.Utils.OAuth.Provider;
using DevExpress.XtraRichEdit.Model;
using System.Diagnostics;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraTab;
using DevExpress.XtraRichEdit;
using DevExpress.XtraPrinting;

namespace PMSGSC.App
{
    public partial class frmComponentHierachy : DevExpress.XtraEditors.XtraForm
    {
        #region Common Field
        frmMain objMain = new frmMain();
        #endregion

        #region Job Field

        private bool isJobChanged;
        Status statusJob = Status.Update;
        private Job job;

        #endregion

        #region Equipment Field

        private bool isChanged = false; // biến xác định dữ liệu đã thay đổi chưa ?
        List<Equipment> ListEquipmentUpdated = new List<Equipment>(); // mảng lưu tất cả sự thay đổi sảy ra
        List<Equipment> ListEquipment = new List<Equipment>(); // mảng lấy tất cả các equipment để tạo Treeview
        private TreeNode CURRENT_NODE = null; // Equipment hiện hành
        private TreeNode CURRENT_NEW_NODE = null; // New Equipment hiện hành
        private TreeNode dragNode = null; // Equipment được kéo qua vị trí khác
        private TreeNode tempDropNode = null; // Vị trí lưu equipment bị kéo
        private Timer timer = new Timer(); // Thời gian để refresh lại equipment bị kéo
        Status status = Status.Update; // Trạng thai hiện hành đang làm gì ( Update, New)
        Font MyFont = new Font("Microsoft Sans Serif", 8.5F, FontStyle.Underline, GraphicsUnit.Point);
        List<InfoCurrentNode> infoCurrentNode = new List<InfoCurrentNode>();

        #endregion

        #region Common
        public frmComponentHierachy(frmMain fMain)
        {
            InitializeComponent();

            timer.Interval = 200;
            timer.Tick += new EventHandler(timer_Tick);
            ListEquipment = Equipment_BLL.GetAll(frmMain.ship.Ship_ID);
            CreateTree();
            tvEquipment.DrawMode = TreeViewDrawMode.OwnerDrawText;
            tvEquipment.DrawNode += new DrawTreeNodeEventHandler(tvEquipment_DrawNode);
            objMain = fMain;

            LoadDataSource();
        }
        private void LoadDataSource()
        {
            statusBindingSource.DataSource = Status_BLL.GetAll(frmMain.ship.Ship_ID);
            locationBindingSource.DataSource = Location_BLL.GetAll(frmMain.ship.Ship_ID);
        }
        private void LoadDataIntoTabPage()
        {
            XtraTabPage tabpage = tabCotrolComponent.SelectedTabPage;
            if (CURRENT_NODE != null && CURRENT_NODE.Name != "0" && CURRENT_NODE.Name != "-1")
            {
                switch (tabpage.Name)
                {
                    case "Jobs":
                        jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), frmMain.ship.Ship_ID, false);
                        job = jobBindingSource.Current as Job;
                        employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
                        serviceCodeBindingSource.DataSource = ServiceCode_BLL.GetAll(frmMain.ship.Ship_ID);

                        if (jobBindingSource.Count > 0)
                            ucLoadJobDescription1.id = job.JobDescription_ID.Value;

                        ShowTimeUnitCombo();
                        LoadDataIntoTabPageJob(tabpage);
                        break;
                    case "Parts":
                        partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                        makerBindingSource.DataSource = Maker_BLL.GetAll(frmMain.ship.Ship_ID);
                        vendorBindingSource.DataSource = Vendor_BLL.GetAll(frmMain.ship.Ship_ID);
                        break;
                    case "Attachments":
                        attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                        isChangedA = false;
                        break;
                    case "WO":
                        workOrderBindingSource.DataSource = WorkOrder_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), frmMain.ship.Ship_ID, false);
                        break;
                    case "Counter":
                        equipmentBindingSource.DataSource = Equipment_BLL.GetDataById(int.Parse(CURRENT_NODE.Name));
                        break;
                    case "History":
                        historyBindingSource.DataSource = History_BLL.GetAllByEquipment(int.Parse(CURRENT_NODE.Name));
                        break;
                }
            }
            else
            {
                switch (tabpage.Name)
                {
                    case "Jobs":
                        jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(0, frmMain.ship.Ship_ID, false);
                        ucLoadJobDescription1.SetValue("", "", "");
                        LoadDataIntoTabPageJob(tabpage);
                        break;
                    case "Parts":
                        partsInEquipmentBindingSource.DataSource = null;
                        makerBindingSource.DataSource = null;
                        vendorBindingSource.DataSource = null;
                        break;
                    case "Attachments":
                        attachmentBindingSource.DataSource = null;
                        break;
                    case "WO":
                        workOrderBindingSource.DataSource = null;
                        break;
                    case "Counter":
                        equipmentBindingSource.DataSource = null;
                        break;
                    case "History":
                        historyBindingSource.DataSource = null;
                        break;

                }

            }
        }
        #endregion

        #region Function of Hierachy Equipment

        //private void CreateTree()
        //{
        //    int n = 0;
        //    int i = 0;
        //    InfoCurrentNode item = new InfoCurrentNode();

        //    TreeNode treeNode = new TreeNode();
        //    treeNode.Text = "Component";
        //    treeNode.Name = "0";
        //    tvEquipment.Nodes.Add(treeNode);

        //    List<Equipment> listEquip = GetDataByParentID(0);
        //    n = listEquip.Count;

        //    item.Node = treeNode;
        //    item.Count = listEquip.Count;
        //    item.Index = i;
        //    item.Id = 0;
        //    infoCurrentNode.Add(item);
        //    while (true)
        //    {
        //        listEquip = GetDataByParentID(infoCurrentNode[infoCurrentNode.Count - 1].Id);
        //        n = listEquip.Count;
        //        do
        //        {
        //            TreeNode newNode = new TreeNode();
        //            newNode.Text = listEquip[i].NameEquipment;
        //            newNode.Name = listEquip[i].Equipment_ID.ToString();
        //            infoCurrentNode[infoCurrentNode.Count - 1].Node.Nodes.Add(newNode);
        //            List<Equipment> childEquip = GetDataByParentID(listEquip[i].Equipment_ID);
        //            if (childEquip.Count > 0)
        //            {
        //                item.Node = newNode;
        //                item.Count = childEquip.Count;
        //                item.Index = i;
        //                item.Id = listEquip[i].Equipment_ID;
        //                infoCurrentNode.Add(item);
        //                break;
        //            }
        //            i++;
        //            if (i == n)
        //            {
        //                infoCurrentNode.RemoveAt(infoCurrentNode.Count - 1);
        //                i = infoCurrentNode[infoCurrentNode.Count - 1].Index;
        //                n = infoCurrentNode[infoCurrentNode.Count - 1].Count;
        //                i++;
        //            }
        //        } while (i < n);

        //    }
        //}


        //  Hàm tạo cây thiết bị

        private void CreateTree()
        {
            TreeNode treeNode = new TreeNode();
            treeNode.Text = "COMPONENT";
            treeNode.Name = "0";
            tvEquipment.Nodes.Add(treeNode);
            CreateNode(treeNode, 0);
            tvEquipment.ShowNodeToolTips = true;
        }

        //Đệ quy tạo cây thiết bị
        private void CreateNode(TreeNode Tree, int ParentID)
        {
            List<Equipment> listEquip = GetDataByParentID(ParentID);
            if (listEquip.Count > 0)
            {
                foreach (Equipment e in listEquip)
                {
                    TreeNode newNode = new TreeNode();
                    // newNode.Text = " [ " + e.CodeEquipment + "  ] ";
                    newNode.Text = e.NameEquipment;
                    newNode.Name = e.Equipment_ID.ToString();
                    Tree.Nodes.Add(newNode);
                    if (GetDataByParentID(e.Equipment_ID).ToList().Count > 0)
                    {
                        CreateNode(newNode, e.Equipment_ID);
                    }
                }
            }
        }

        // Lấy Equipment theo ParentID để tạo cây
        private List<Equipment> GetDataByParentID(int ParentID)
        {
            List<Equipment> Temp = new List<Equipment>();
            foreach (Equipment e in ListEquipment)
            {
                if (e.ParentID == ParentID)
                {
                    Temp.Add(e);
                }
            }
            return Temp;
        }

        void tvEquipment_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            if ((e.State & TreeNodeStates.Hot) == TreeNodeStates.Hot)
            {
                // Lấy font , màu chữ của node
                Font nodeFont = GetTreeNodeFont(e.Node);
                Color nodeForeColor = GetTreeNodeForeColor(e.Node, e.State);
                nodeForeColor = Color.CadetBlue;
                // Vẽ text node ra ngoài
                TextRenderer.DrawText(e.Graphics, e.Node.Text, nodeFont, e.Bounds, nodeForeColor, TextFormatFlags.Left | TextFormatFlags.Top);
                e.Node.ToolTipText = e.Node.Text;
                // vẽ viền của node được chọn
                if ((e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected)
                {
                    using (Pen pen = new Pen(nodeForeColor))
                    {
                        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                        Rectangle penBounds = e.Bounds;
                        penBounds.Width -= 1;
                        penBounds.Height -= 1;
                        e.Graphics.DrawRectangle(pen, penBounds);
                    }
                }
            }
            else
            {
                e.DrawDefault = true;
            }
        }

        // Lấy font của node
        private Font GetTreeNodeFont(TreeNode node)
        {
            Font nodeFont = node.NodeFont;
            if (nodeFont == null)
            {
                nodeFont = MyFont;
            }
            return nodeFont;
        }

        // Lấy màu chữ của node
        private Color GetTreeNodeForeColor(TreeNode node, TreeNodeStates nodeState)
        {
            Color nodeForeColor = Color.Empty;

            if ((nodeState & TreeNodeStates.Selected) == TreeNodeStates.Selected)
            {
                nodeForeColor = Color.FromKnownColor(KnownColor.HighlightText);
            }
            else
            {
                nodeForeColor = node.ForeColor;
                if (nodeForeColor == Color.Empty)
                {
                    nodeForeColor = this.ForeColor;
                }
            }

            return nodeForeColor;
        }

        // Kiểm tra xem thiết bị hiện tại đã có trong mảnh phụ chưa
        private Equipment GetEquipmentInList(int id)
        {
            foreach (Equipment e in ListEquipmentUpdated)
            {
                if (e.Equipment_ID == id)
                {
                    return e;
                }
            }
            return null;
        }

        // Sự kiện click vào 1 thiết bị trên cây
        private void treevHeThongThietBi_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            statusJob = Status.Update;
            TreeNode node = e.Node as TreeNode;
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                tvEquipment.BeginUpdate();
                this.tvEquipment.SelectedNode = e.Node;
                e.Node.ContextMenuStrip = cmstvEquipment;
                e.Node.ContextMenuStrip.Show(MousePosition);
                tvEquipment.EndUpdate();
            }

            if (isChanged || ucLoadMaker1.isChanges || ucLoadVendor1.isChanges || ucRichEditControl1.isChange)
            {
                SaveEquipmentChanged();
                ucLoadMaker1.isChanges = false;
                ucLoadVendor1.isChanges = false;
                ucRichEditControl1.isChange = false;
            }

            CURRENT_NODE = node;
            ShowValueWhenClicked(node);
        }

        //Show value
        private void ShowValueWhenClicked(TreeNode node)
        {
            Equipment equip = null;
            if (node.Name != "0")
            {
                equip = GetEquipmentInList(int.Parse(node.Name));
                if (null != equip)
                {
                    ShowDisplayValue(equip);
                }
                else
                {
                    equip = Equipment_BLL.GetDataById(int.Parse(node.Name));

                    if (null != equip)
                        ShowDisplayValue(equip);
                    else
                        RefreshDisplayValue();
                }
                //    objMain.lbTitle.Text = "Component Hierachy -> [ " + equip.CodeEquipment + " ] " + equip.NameEquipment;
            }
            else
            {
                RefreshDisplayValue();
                //    objMain.lbTitle.Text = "Component Hierachy -> [ . . ] " + CURRENT_NODE.Text;
            }
            LoadDataIntoTabPage();
        }

        // Save thiết bị đã có sự thay đổi vào mảng tạm
        private void SaveEquipmentChanged()
        {
            Equipment equip;

            equip = GetEquipmentInList(int.Parse(CURRENT_NODE.Name));
            if (null != equip)
            {
                ListEquipmentUpdated.Remove(equip);

                equip.Equipment_ID = int.Parse(CURRENT_NODE.Name);
                equip.ParentID = int.Parse(CURRENT_NODE.Parent.Name);
                equip.NameEquipment = CURRENT_NODE.Text;
            }
            else
            {
                equip = Equipment_BLL.GetDataById(int.Parse(CURRENT_NODE.Name));
            }

            if (equip != null)
            {
                SetValue(equip);
                ListEquipmentUpdated.Add(equip);
            }
            isChanged = false;
        }

        // Nếu vị trí lưu thiết bị thay đổi thì cập nhật lại mảng tạm
        private void PositionEquipmentChanged()
        {
            Equipment equip = GetEquipmentInList(int.Parse(CURRENT_NODE.Name));
            if (equip != null)
            {
                ListEquipmentUpdated.Remove(equip);
            }
            if (CURRENT_NODE.Name != "-1")
            {
                equip = Equipment_BLL.GetDataById(int.Parse(CURRENT_NODE.Name));
                equip.ParentID = int.Parse(CURRENT_NODE.Parent.Name);
            }
            else
            {
                equip.Equipment_ID = int.Parse(CURRENT_NODE.Name);
                equip.ParentID = int.Parse(CURRENT_NODE.Parent.Name);
                equip.Ship_ID = frmMain.ship.Ship_ID;
            }
            ListEquipmentUpdated.Add(equip);
            isChanged = false;
        }

        // Refresh lại giá trị các text trên màn hình
        private void RefreshDisplayValue()
        {
            txtNumber.Text = "";
            txtName.Text = "";
            txtSerial.Text = "";
            gluStatus.Text = "";
            ucLoadMaker1.SetValue("", "", "");
            ucLoadVendor1.SetValue("", "", "");
            ucRichEditControl1.richEditControl1.Text = "";
            txtParentNameComp.Text = "";
            txtParentCodeComp.Text = "";
            gluLocation.Text = "";
        }

        // Show dữ liệu lên màng hình 
        private void ShowDisplayValue(Equipment selectEquip)
        {
            txtNumber.Text = selectEquip.CodeEquipment;
            txtName.Text = selectEquip.NameEquipment;
            txtSerial.Text = selectEquip.Serial;

            gluStatus.EditValue = selectEquip.Status_ID;

            if (selectEquip.Maker != null)
                ucLoadMaker1.SetValue(selectEquip.Maker.CodeMaker, selectEquip.Maker.NameMaker, selectEquip.Maker.Maker_ID.ToString());
            else
                ucLoadMaker1.SetValue("", "", "");

            if (selectEquip.Vendor != null)
                ucLoadVendor1.SetValue(selectEquip.Vendor.CodeVendor, selectEquip.Vendor.NameVendor, selectEquip.Vendor.Vendor_ID.ToString());
            else
                ucLoadVendor1.SetValue("", "", "");


            gluLocation.EditValue = selectEquip.Location_ID;
            ucRichEditControl1.richEditControl1.Text = selectEquip.Details;

            if (selectEquip.ParentID != 0)
            {
                Equipment parentEquip = GetEquipmentInList(selectEquip.ParentID);
                if (parentEquip == null)
                    parentEquip = Equipment_BLL.GetDataById(selectEquip.ParentID);

                txtParentCodeComp.Text = parentEquip.CodeEquipment;
                txtParentNameComp.Text = parentEquip.NameEquipment;
            }
            else
            {
                txtParentCodeComp.Text = "";
                txtParentNameComp.Text = "COMPONENT";
            }
        }

        // Lấy giá trị từ các text trên màn hình 
        private void SetValue(Equipment equip)
        {
            equip.CodeEquipment = txtNumber.Text;
            equip.NameEquipment = txtName.Text;
            equip.Serial = txtSerial.Text;

            if (ucLoadMaker1.lb_id.Text != "")
                equip.Maker = BaseDAL.DB.Makers.Single(c => c.Maker_ID == int.Parse(ucLoadMaker1.lb_id.Text));

            if (ucLoadVendor1.lbid.Text != "")
                equip.Vendor = BaseDAL.DB.Vendors.Single(c => c.Vendor_ID == int.Parse(ucLoadVendor1.lbid.Text));

            if (gluStatus.Text != "")
                equip.Status_ID = int.Parse(gluStatus.EditValue.ToString());

            if (gluLocation.Text != "")
                equip.Location_ID = int.Parse(gluLocation.EditValue.ToString());

            equip.Details = ucRichEditControl1.richEditControl1.Text;
            equip.Ship_ID = frmMain.ship.Ship_ID;
        }

        // Sự kiện kéo một thiết bị
        private void treevHeThongThietBi_ItemDrag(object sender, ItemDragEventArgs e)
        {
            this.dragNode = (TreeNode)e.Item;
            if (this.dragNode.Name == "0")
            {
                tvEquipment.AllowDrop = false;
            }
            else
            {
                tvEquipment.AllowDrop = true;
            }
            this.tvEquipment.SelectedNode = this.dragNode;

            this.imageListDrag.Images.Clear();
            this.imageListDrag.ImageSize = new Size(this.dragNode.Bounds.Size.Width + this.tvEquipment.Indent, this.dragNode.Bounds.Height);

            Bitmap bmp = new Bitmap(this.dragNode.Bounds.Width + this.tvEquipment.Indent, this.dragNode.Bounds.Height);

            Graphics gfx = Graphics.FromImage(bmp);

            gfx.DrawImage(this.imageListTreeView.Images[0], 0, 0);

            gfx.DrawString(this.dragNode.Text,
                this.tvEquipment.Font,
                new SolidBrush(this.tvEquipment.ForeColor),
                (float)this.tvEquipment.Indent, 1.0f);

            this.imageListDrag.Images.Add(bmp);

            Point p = this.tvEquipment.PointToClient(Control.MousePosition);

            int dx = p.X + this.tvEquipment.Indent - this.dragNode.Bounds.Left;
            int dy = p.Y - this.dragNode.Bounds.Top + 50;

            if (DragHelper.ImageList_BeginDrag(this.imageListDrag.Handle, 0, dx, dy))
            {
                this.tvEquipment.DoDragDrop(bmp, DragDropEffects.Move);
                DragHelper.ImageList_EndDrag();
            }
        }

        // Sự kiện kéo qua một thiết bị
        private void tvEquipment_DragOver(object sender, DragEventArgs e)
        {

            Point formP = this.PointToClient(new Point(e.X, e.Y));
            DragHelper.ImageList_DragMove(formP.X - this.tvEquipment.Left, formP.Y - this.tvEquipment.Top);

            TreeNode dropNode = this.tvEquipment.GetNodeAt(this.tvEquipment.PointToClient(new Point(e.X, e.Y)));
            if (dropNode == null)
            {
                e.Effect = DragDropEffects.None;
                return;
            }
            if (int.Parse(dropNode.Name) < 0)
            {
                e.Effect = DragDropEffects.None;
                return;
            }
            e.Effect = DragDropEffects.Move;

            if (this.tempDropNode != dropNode)
            {
                DragHelper.ImageList_DragShowNolock(false);
                this.tvEquipment.SelectedNode = dropNode;
                DragHelper.ImageList_DragShowNolock(true);
                tempDropNode = dropNode;
            }
            TreeNode tmpNode = dropNode;
            while (tmpNode.Parent != null)
            {
                if (tmpNode.Parent == this.dragNode) e.Effect = DragDropEffects.None;
                tmpNode = tmpNode.Parent;
            }
        }

        // Sự kiện kéo vào 1 thiết bị rồi buông chuột
        private void tvEquipment_DragDrop(object sender, DragEventArgs e)
        {
            DragHelper.ImageList_DragLeave(this.tvEquipment.Handle);
            TreeNode dropNode = this.tvEquipment.GetNodeAt(this.tvEquipment.PointToClient(new Point(e.X, e.Y)));
            if (this.dragNode != dropNode)
            {
                if (this.dragNode.Parent == null)
                    this.tvEquipment.Nodes.Remove(this.dragNode);
                else
                    this.dragNode.Parent.Nodes.Remove(this.dragNode);

                dropNode.Nodes.Add(this.dragNode);
                dropNode.Expand();
                isChanged = true;
                tvEquipment.SelectedNode = this.dragNode;
                CURRENT_NODE = this.dragNode;
                PositionEquipmentChanged();
                Equipment equip = Equipment_BLL.GetDataById(int.Parse(dragNode.Name));
                if (equip != null)
                {
                    ShowDisplayValue(equip);
                }
                else
                {
                    equip = GetEquipmentInList(int.Parse(dragNode.Name));
                    if (equip != null)
                        ShowDisplayValue(equip);
                    else
                        RefreshDisplayValue();
                }
                this.dragNode = null;
                this.timer.Enabled = false;
            }
        }

        // Sự kiện kéo vào 1 thiết bị
        private void tvEquipment_DragEnter(object sender, DragEventArgs e)
        {
            DragHelper.ImageList_DragEnter(this.tvEquipment.Handle, e.X - this.tvEquipment.Left,
              e.Y - this.tvEquipment.Top);

            this.timer.Enabled = true;
        }

        // Sự kiện kéo ra một thiết bị
        private void tvEquipment_DragLeave(object sender, EventArgs e)
        {
            DragHelper.ImageList_DragLeave(this.tvEquipment.Handle);

            this.timer.Enabled = false;
        }

        // Sự kiện trả ngược lại khi vị trí bị giới hạn
        private void tvEquipment_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            if (e.Effect == DragDropEffects.Move)
            {
                e.UseDefaultCursors = false;
                this.tvEquipment.Cursor = Cursors.Default;
            }
            else e.UseDefaultCursors = true;
        }

        // Đếm thời gian để cập nhận lại icon kéo
        private void timer_Tick(object sender, EventArgs e)
        {
            Point pt = PointToClient(Control.MousePosition);
            TreeNode node = this.tvEquipment.GetNodeAt(pt);

            if (node == null) return;

            if (pt.Y < 30)
            {
                if (node.PrevVisibleNode != null)
                {
                    node = node.PrevVisibleNode;

                    DragHelper.ImageList_DragShowNolock(false);
                    node.EnsureVisible();
                    this.tvEquipment.Refresh();
                    DragHelper.ImageList_DragShowNolock(true);

                }
            }
            else if (pt.Y > this.tvEquipment.Size.Height - 30)
            {
                if (node.NextVisibleNode != null)
                {
                    node = node.NextVisibleNode;

                    DragHelper.ImageList_DragShowNolock(false);
                    node.EnsureVisible();
                    this.tvEquipment.Refresh();
                    DragHelper.ImageList_DragShowNolock(true);
                }
            }
        }

        // Sự kiện thêm một thiết bị
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var hitTest = tvEquipment.HitTest(tvEquipment.PointToClient(new Point(cmstvEquipment.Left, cmstvEquipment.Top)));
            if (null != hitTest)
            {
                tvEquipment.SelectedNode = hitTest.Node;
                if (status == Status.Update)
                {
                    try
                    {
                        status = Status.New;
                        TreeNode newNode = new TreeNode();
                        CreateNewNode(newNode);
                        CURRENT_NEW_NODE = newNode;
                    }
                    catch
                    {
                        status = Status.Update;
                    }
                }
            }
        }

        // Xóa một thiết bị trong mảng tạm
        private void RemoveNewEquipment()
        {
            for (int i = 0; i < ListEquipmentUpdated.Count; i++)
            {
                if (ListEquipmentUpdated[i].Equipment_ID < 0)
                {
                    ListEquipmentUpdated.RemoveAt(i);
                }
            }
        }

        // Xóa 1 Thiết bị
        private void DeleteNode()
        {
            TreeNode selectNode = tvEquipment.SelectedNode;
            if (selectNode.Parent == null)
                tvEquipment.Nodes.Remove(selectNode);
            else
                selectNode.Parent.Nodes.Remove(selectNode);

            if (selectNode.Name != "-1")
            {
                Equipment equip = Equipment_BLL.GetDataById(int.Parse(selectNode.Name));
                bool result = Equipment_BLL.Delete(equip);
                DeleteChildNode(int.Parse(selectNode.Name));

            }
            else
            {
                status = Status.Update;
            }
        }

        // Nếu thiết bị có con thì đệ quy xuống 
        private void DeleteChildNode(int ParentID)
        {
            List<Equipment> childEquipment = GetDataByParentID(ParentID);
            if (childEquipment.Count > 0)
            {
                foreach (Equipment e in childEquipment)
                {
                    Equipment_BLL.Delete(e);
                    DeleteChildNode(e.Equipment_ID);
                }
            }
        }

        // Sự kiện xóa một thiết bị
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var hitTest = tvEquipment.HitTest(tvEquipment.PointToClient(new Point(cmstvEquipment.Left, cmstvEquipment.Top)));
            if (null != hitTest.Node)
            {
                tvEquipment.SelectedNode = hitTest.Node;
                if (tvEquipment.SelectedNode.Name != "0")
                {
                    if (XtraMessageBox.Show("Do you want to delete this Equipment ?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                    {
                        if (Equipment_BLL.TestBeforeDeleteComponentFinal(int.Parse(tvEquipment.SelectedNode.Name)))
                        {
                            if (ListEquipmentUpdated.Count > 0)
                            {
                                XtraMessageBox.Show("The data has changed ! Please save and refresh hierachy equipment", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }
                            else
                            {
                                DeleteNode();
                                CURRENT_NODE = tvEquipment.SelectedNode;
                                ShowValueWhenClicked(CURRENT_NODE);
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show("Cann't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                }

            }
        }

        string selectedNodeText;
        // Sự kiện sửa tên một thiết bị
        private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (null != this.tvEquipment.SelectedNode)
            {
                TreeNode node = this.tvEquipment.SelectedNode as TreeNode;
                selectedNodeText = node.Text;
                node.Text = txtName.Text;
                this.tvEquipment.LabelEdit = true;
                node.BeginEdit();
            }
        }

        // Đổi tên thiết bị ràng buộc tên nhập vào
        private void tvEquipment_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            try
            {
                TreeNode node = this.tvEquipment.SelectedNode as TreeNode;
                this.tvEquipment.LabelEdit = false;
                string label = (null != e.Label ? e.Label : selectedNodeText);
                txtName.Text = label;
                isChanged = true;
            }
            catch
            {
            }
        }

        // Sự kiện click vào usercontrol để show contextmenuShip
        private void ucComponentHierachy_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                this.ContextMenuStrip.Show(MousePosition);
            }
        }

        // Sự kiện save
        private void saveChangedF5ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveEquipment();
        }

        // Thêm một thiết bị

        public void NewComponent()
        {
            if (status == Status.Update)
            {

                if (isChanged || ucLoadMaker1.isChanges || ucLoadVendor1.isChanges)
                {
                    SaveEquipmentChanged();
                    ucLoadMaker1.isChanges = false;
                    ucLoadVendor1.isChanges = false;
                }

                try
                {
                    status = Status.New;
                    TreeNode newNode = new TreeNode();
                    CreateNewNode(newNode);
                    CURRENT_NEW_NODE = newNode;
                }
                catch
                {
                    status = Status.Update;
                    //  XtraMessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // Theo một node thiết bị thêm vào cây
        private void CreateNewNode(TreeNode newNode)
        {
            newNode.Text = "";
            newNode.Name = "-1";
            tvEquipment.SelectedNode.Nodes.Add(newNode);
            tvEquipment.SelectedNode.Expand();

            Equipment newEquip = new Equipment();
            newEquip.Equipment_ID = -1;
            newEquip.Ship_ID = frmMain.ship.Ship_ID;
            newEquip.ParentID = int.Parse(tvEquipment.SelectedNode.Name);
            ListEquipmentUpdated.Add(newEquip);

            tvEquipment.SelectedNode = newNode;
            CURRENT_NODE = tvEquipment.SelectedNode;

            RefreshDisplayValue();
            LoadDataIntoTabPage();
        }

        // Save tất cả sự thay đổi
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveAll();
        }

        //   Save All
        private void SaveAll()
        {
            if (XtraMessageBox.Show("Do you want to save all changes ?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                SaveEquipment();
                SaveAllJob();

            }
            else
            {
                ListEquipmentUpdated.Clear();
                if (CURRENT_NEW_NODE != null)
                {
                    status = Status.Update;
                    DeleteNewNode();
                }
            }
        }

        // Delete Node
        private void DeleteNewNode()
        {
            if (CURRENT_NEW_NODE.Parent == null)
                tvEquipment.Nodes.Remove(CURRENT_NEW_NODE);
            else
                CURRENT_NEW_NODE.Parent.Nodes.Remove(CURRENT_NEW_NODE);

            CURRENT_NEW_NODE = null;
        }

        // Hàm save tất cả
        public void SaveEquipment()
        {
            if (isChanged || ucLoadMaker1.isChanges || ucLoadVendor1.isChanges)
            {
                SaveEquipmentChanged();
                ucLoadMaker1.isChanges = false;
                ucLoadVendor1.isChanges = false;
            }
            if (ListEquipmentUpdated.Count > 0)
            {
                foreach (Equipment e in ListEquipmentUpdated)
                {
                    if (e.Equipment_ID > 0)
                    {
                        bool result = Equipment_BLL.Update(e);
                    }
                    else
                    {
                        if (e.CodeEquipment != null && e.CodeEquipment != "" && e.CodeEquipment != "   .   .   ")
                        {
                            e.CurrentCounter = 0;
                            e.OldCounter = 0;
                            bool result = Equipment_BLL.Insert(e);
                            CURRENT_NEW_NODE.Name = Equipment_BLL.GetLastEquipmentID().ToString();
                        }
                    }
                }
                status = Status.Update;
                ListEquipmentUpdated.Clear();
                if (CURRENT_NEW_NODE != null)
                    CURRENT_NEW_NODE = null;

            }
        }
        // Sự kiện refresh lại cây thiết bị
        private void refeshFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshDisplay();
        }
        // Sự kiện refresh lại cây thiết bị
        private void RefreshTreeView()
        {
            status = Status.Update;
            ListEquipmentUpdated.Clear();
            ListEquipment = Equipment_BLL.GetAll(frmMain.ship.Ship_ID);
            tvEquipment.Nodes.Clear();
            CreateTree();
        }
        // Kiểm tra nếu có sự thây đổi sảy ra 
        private void txtNumber_TextChanged(object sender, EventArgs e)
        {
            if (txtNumber.ContainsFocus && CURRENT_NODE != null)
            {
                if (CURRENT_NODE.Name != "0")
                {
                    isChanged = true;
                }
            }
        }
        // Kiểm tra nếu có sự thây đổi sảy ra 
        private void txtName_TextChanged(object sender, EventArgs e)
        {
            if (txtName.ContainsFocus && CURRENT_NODE != null)
            {
                if (CURRENT_NODE.Name != "0")
                {
                    isChanged = true;
                }
            }
        }

        // Kiểm tra nếu có sự thây đổi sảy ra 
        private void txtSerial_TextChanged(object sender, EventArgs e)
        {
            if (txtSerial.ContainsFocus && CURRENT_NODE != null)
            {
                if (CURRENT_NODE.Name != "0")
                {
                    isChanged = true;
                }
            }
        }

        // Kiểm tra nếu có sự thây đổi sảy ra 
        private void gluStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (gluStatus.ContainsFocus && CURRENT_NODE != null)
            {
                if (CURRENT_NODE.Name != "0")
                {
                    isChanged = true;
                }
            }
        }

        private void gluLocation_EditValueChanged(object sender, EventArgs e)
        {
            if (gluLocation.ContainsFocus && CURRENT_NODE != null)
            {
                if (CURRENT_NODE.Name != "0")
                {
                    isChanged = true;
                }
            }
        }

        // Gán tên thiết bị vừa nhập vào cây
        private void txtName_Leave(object sender, EventArgs e)
        {
        }

        // Refresh lại cây thiết bị
        private void refeshF5ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshDisplay();
        }

        // Save tất cả
        private void saveChangeF5ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            SaveChanged();
        }

        private void SaveChanged()
        {
            XtraTabPage tabpage = tabCotrolComponent.SelectedTabPage;
            switch (tabpage.Name)
            {
                case "Jobs":
                    SaveAllJob();
                    break;
                case "General":
                    SaveEquipment();
                    break;
            }
        }

        // Refresh lại cây thiết bị
        private void refeshF5ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            RefreshDisplay();
        }

        // Refresh lại cây thiết bị
        private void RefreshDisplay()
        {
            if (ListEquipmentUpdated.Count > 0)
                SaveAll();


            CURRENT_NODE = null;
            RefreshDisplayValue();
            RefreshTreeView();
            LoadDataIntoTabPage();
            attachmentBindingSource.DataSource = null;
        }

        private void txtNumber_Validating(object sender, CancelEventArgs e)
        {
            if (CURRENT_NODE != null && CURRENT_NODE.Name != "0")
            {
                Equipment eq = new Equipment();
                eq.CodeEquipment = txtNumber.Text;
                eq.Equipment_ID = int.Parse(CURRENT_NODE.Name);
                if (Equipment_BLL.IsExits(eq))
                {
                    XtraMessageBox.Show("Number Code has exitsed in the database", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
                if (tvEquipment.SelectedNode != null)
                {
                    // tvEquipment.SelectedNode.Text = " [ " + txtNumber.Text + " ] ";
                    tvEquipment.SelectedNode.Text = txtName.Text;
                }
            }
        }

        public bool FindComponent(string Info, int type)
        {
            isFinded = false;
            if (type == 0)
            {
                Equipment equip = Equipment_BLL.GetDataByNumber(Info);
                return Find(tvEquipment.Nodes, equip.Equipment_ID);
            }
            else
            {
                return Find(tvEquipment.Nodes, Info);
            }
        }

        public bool Find(TreeNodeCollection Collection, int id)
        {
            foreach (TreeNode node in Collection)
            {
                if (node.Name == id.ToString())
                {
                    CURRENT_NODE = node;
                    ShowValueWhenClicked(node);
                    tvEquipment.SelectedNode = node;
                    node.Expand();
                    isFinded = true;
                }
                if (node.Nodes.Count > 0)
                {
                    Find(node.Nodes, id);
                }
            }
            return isFinded;
        }

        bool isFinded;
        public bool Find(TreeNodeCollection Collection, string Name)
        {
            foreach (TreeNode node in Collection)
            {

                if (node.Text == Name)
                {
                    CURRENT_NODE = node;
                    ShowValueWhenClicked(node);
                    tvEquipment.SelectedNode = node;
                    node.Expand();
                    isFinded = true;
                }

                if (node.Nodes.Count > 0)
                {
                    Find(node.Nodes, Name);
                }

            }
            return isFinded;
        }

        private void findF3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmFindOnTree objFind = new frmFindOnTree(this);
            objFind.ShowDialog();
        }
        #endregion

        #region Job

        private void ShowTimeUnitCombo()
        {
            nextDueDateEdit.Enabled = false;
            if (job != null)
                cbbTimeUnit.SelectedIndex = GetIndexInCombobox(job.TimeUnit);
            else
            {
                cbbTimeUnit.SelectedIndex = -1;
            }
        }

        private void DenableAllControl()
        {
            ucLoadJobDescription1.Enabled = false;
            employee_IDGridLookUpEdit.Enabled = false;
            ucLoadJobDescription1.Enabled = false;
            employee_IDGridLookUpEdit.Enabled = false;
            sC_IDGridLookUpEdit.Enabled = false;
            freodicFrequencyTextEdit.Enabled = false;
            alarmDaybeforeTextEdit.Enabled = false;
            lastDoneDateEdit.Enabled = false;
        }

        private void jobDescription_IDGridLookUpEditView_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        XtraTabPage tabpage = new XtraTabPage();
        private void xtraTabControl5_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            tabpage = xtraTabControl5.SelectedTabPage;
            LoadDataIntoTabPageJob(tabpage);
        }

        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

        private bool TestBeforeAddJob()
        {
            if (tvEquipment.SelectedNode != null && tvEquipment.SelectedNode.Name != "-1" && tvEquipment.SelectedNode.Name != "0")
                return true;
            return false;
        }

        private bool TestBeforeAddPartJob()
        {
            if (job != null && job.Job_ID != 0)
                return true;

            return false;
        }

        private void LoadDataIntoTabPageJob(XtraTabPage tabpage)
        {
            if (job != null && job.Job_ID != 0)
            {
                switch (tabpage.Name)
                {
                    case "RP":
                        jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(job.Job_ID, false);
                        isChangedA = false;
                        gridView15.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
                        break;
                    case "AJ":
                        attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(job.Job_ID, isChangedA);
                        gridView13.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
                        //  isChangedAJ = false;
                        break;
                }
            }
            else
            {
                switch (tabpage.Name)
                {
                    case "RP":
                        jobPartBindingSource.DataSource = null;
                        gridView15.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
                        break;
                    case "AJ":
                        attachmentsJobBindingSource.DataSource = null;
                        gridView13.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
                        break;
                }

            }
        }
        private void btnNewJob_Click(object sender, EventArgs e)
        {
            if (TestBeforeAddJob())
            {
                if (statusJob == Status.Update)
                {
                    EnableAllControl();

                    statusJob = Status.New;
                    job = jobBindingSource.AddNew() as Job;
                    job.Job_ID = 0;
                    job.TimeUnit = "Hour(s)";
                    job.TimeDone = 0;
                    job.SC_ID = 2;
                    job.Equipment_ID = int.Parse(CURRENT_NODE.Name);
                    ucLoadJobDescription1.SetValue("", "", "");
                }
                else
                {
                    XtraMessageBox.Show("Please save current new Job. Before add new a Job", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                XtraMessageBox.Show("No component selected !!!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void EnableAllControl()
        {
            ucLoadJobDescription1.Enabled = true;
            employee_IDGridLookUpEdit.Enabled = true;
            ucLoadJobDescription1.Enabled = true;
            employee_IDGridLookUpEdit.Enabled = true;
            sC_IDGridLookUpEdit.Enabled = true;
            freodicFrequencyTextEdit.Enabled = true;
            alarmDaybeforeTextEdit.Enabled = true;
            lastDoneDateEdit.Enabled = true;
        }

        private void xtraTabControl3_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            LoadDataIntoTabPage();
        }

        private int GetLastTwoNumber(int year)
        {
            return year % 1000;
        }

        public void SaveAllJob()
        {
            if (job != null)
            {
                SetValueInsertJob(job);
                if (isJobChanged)
                {
                    if (ucLoadJobDescription1.lbid.Text == "")
                    {
                        XtraMessageBox.Show("Job description cannot be empty", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    for (int i = 0; i < jobBindingSource.Cast<Job>().ToList().Count; i++)
                    {
                        if (jobBindingSource.Cast<Job>().ToList()[i].TimeUnit == "Hour(s)")
                        {
                            jobBindingSource.Cast<Job>().ToList()[i].Counter = true;

                            jobBindingSource.Cast<Job>().ToList()[i].LastDone = null;
                            jobBindingSource.Cast<Job>().ToList()[i].NextDue = null;
                            jobBindingSource.Cast<Job>().ToList()[i].AlarmDaybefore = null;
                        }
                        else
                        {
                            jobBindingSource.Cast<Job>().ToList()[i].Counter = false;
                            jobBindingSource.Cast<Job>().ToList()[i].TimeDone = null;

                            if (jobBindingSource.Cast<Job>().ToList()[i].LastDone != null && jobBindingSource.Cast<Job>().ToList()[i].FreodicFrequency != null)
                                jobBindingSource.Cast<Job>().ToList()[i].NextDue = NextDue(jobBindingSource.Cast<Job>().ToList()[i].FreodicFrequency.ToString(), jobBindingSource.Cast<Job>().ToList()[i].LastDone.Value, jobBindingSource.Cast<Job>().ToList()[i].TimeUnit);
                        }
                        if (WorkOrder_BLL.GetWorkOrderByJobID(jobBindingSource.Cast<Job>().ToList()[i].Job_ID) == null)
                        {
                            if (jobBindingSource.Cast<Job>().ToList()[i].Job_ID == 0)
                                Job_BLL.Insert(jobBindingSource.Cast<Job>().ToList()[i]);
                            else
                                Job_BLL.Update(jobBindingSource.Cast<Job>().ToList()[i]);




                            Job newJob = Job_BLL.GetLastJob();
                            WorkOrder newWorkOrder = new WorkOrder();
                            newWorkOrder.CreateDate = DateTime.Now.Date;
                            newWorkOrder.Detail = newJob.Details;
                            newWorkOrder.EmployeeCreate = frmMain.UserLogin.Name;
                            newWorkOrder.Equipment_ID = newJob.Equipment_ID.Value;
                            newWorkOrder.Frequency = newJob.FreodicFrequency;
                            newWorkOrder.IsCheck = false;
                            newWorkOrder.LastDone = newJob.LastDone;
                            newWorkOrder.Job_ID = newJob.Job_ID;
                            newWorkOrder.RespDescipline_ID = newJob.Employee_ID;
                            newWorkOrder.SC_ID = newJob.SC_ID;
                            newWorkOrder.Ship_ID = newJob.Equipment.Ship_ID;
                            newWorkOrder.StatusJob_ID = 1;
                            newWorkOrder.TimeUnit = newJob.TimeUnit;
                            newWorkOrder.Title = newJob.JobDescription.CodeJD + "-" + newJob.JobDescription.NameJD;
                            newWorkOrder.Type = 1;
                            newWorkOrder.Complete = false;
                            newWorkOrder.WorkOrderNumber = frmMain.ship.CodeShip + "/" + GetLastTwoNumber(DateTime.Now.Date.Year) + "/" + WorkOrder_BLL.GetQuantityWorkOrder(frmMain.ship.Ship_ID).ToString("00000");

                            if (jobBindingSource.Cast<Job>().ToList()[i].TimeUnit == "Hour(s)")
                            {
                                newWorkOrder.NextDue = null;
                                newWorkOrder.AlarmDaybefore = null;
                                newWorkOrder.TimeDone = newJob.TimeDone;
                            }
                            else
                            {

                                newWorkOrder.TimeDone = null;
                                newWorkOrder.NextDue = newJob.NextDue;
                                newWorkOrder.AlarmDaybefore = newJob.AlarmDaybefore;
                            }
                            WorkOrder_BLL.Insert(newWorkOrder);
                        }
                        else
                        {
                            bool reruls = Job_BLL.Update(jobBindingSource.Cast<Job>().ToList()[i]);
                            WorkOrder oldWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(jobBindingSource.Cast<Job>().ToList()[i].Job_ID);
                            if (oldWorkOrder != null)
                            {
                                oldWorkOrder.Title = jobBindingSource.Cast<Job>().ToList()[i].JobDescription.CodeJD + "-" + jobBindingSource.Cast<Job>().ToList()[i].JobDescription.NameJD;
                                oldWorkOrder.Frequency = jobBindingSource.Cast<Job>().ToList()[i].FreodicFrequency;
                                oldWorkOrder.TimeUnit = jobBindingSource.Cast<Job>().ToList()[i].TimeUnit;
                                if (jobBindingSource.Cast<Job>().ToList()[i].TimeUnit == "Hour(s)")
                                {
                                    oldWorkOrder.NextDue = null;
                                    oldWorkOrder.AlarmDaybefore = null;
                                    oldWorkOrder.TimeDone = jobBindingSource.Cast<Job>().ToList()[i].TimeDone;
                                }
                                else
                                {
                                    oldWorkOrder.TimeDone = null;
                                    oldWorkOrder.NextDue = jobBindingSource.Cast<Job>().ToList()[i].NextDue;
                                    oldWorkOrder.AlarmDaybefore = jobBindingSource.Cast<Job>().ToList()[i].AlarmDaybefore;
                                }
                                WorkOrder_BLL.Update(oldWorkOrder);
                            }
                        }
                    }
                    isJobChanged = false;
                    statusJob = Status.Update;
                }
                jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), frmMain.ship.Ship_ID, true);

            }
        }

        private void SetValueInsertJob(Job j)
        {
            if (freodicFrequencyTextEdit.ContainsFocus && freodicFrequencyTextEdit.Text != "")
                j.FreodicFrequency = int.Parse(freodicFrequencyTextEdit.Text);

            if (lastDoneDateEdit.ContainsFocus && lastDoneDateEdit.Text != "")
                j.LastDone = lastDoneDateEdit.DateTime.Date;

            if (alarmDaybeforeTextEdit.ContainsFocus && alarmDaybeforeTextEdit.Text != "")
                j.AlarmDaybefore = int.Parse(alarmDaybeforeTextEdit.Text);

            if (cbbTimeUnit.ContainsFocus)
                j.TimeUnit = cbbTimeUnit.Text;

            if (ucLoadJobDescription1.isChanges)
            {
                ((Job)gridView12.GetFocusedRow()).JobDescription = BaseDAL.DB.JobDescriptions.Single(c => c.JobDescription_ID == int.Parse(ucLoadJobDescription1.lbid.Text));
                ucLoadJobDescription1.isChanges = false;
            }
            if (ucRichEditControl2.isChange)
            {
                j.Details = ucRichEditControl2.richEditControl1.Text;
                ucRichEditControl2.isChange = false;
            }
        }

        private void btnDeleteJob_Click(object sender, EventArgs e)
        {
            if (job != null)
            {
                if (!Job_BLL.TestBeforeDelete(job))
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    Job_BLL.Delete(job);
                    ucLoadJobDescription1.SetValue("", "", "");
                }


                jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), frmMain.ship.Ship_ID, true);
                statusJob = Status.Update;
            }
        }

        private int GetIndexInCombobox(string value)
        {
            if (value == "Hour(s)")
                return 0;
            if (value == "Day(s)")
                return 1;
            if (value == "Week(s)")
                return 2;
            return 3;
        }

        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        private DateTime NextDue(string Frequency, DateTime LastDone, string TimeUnit)
        {

            int Number = int.Parse(Frequency);
            DateTime dt = LastDone;
            switch (TimeUnit)
            {
                case "Day(s)":
                    dt = dt.AddDays(Number);
                    break;
                case "Week(s)":
                    int NumberDay = Number * 7;
                    dt = dt.AddDays(NumberDay);
                    break;
                case "Month(s)":
                    dt = dt.AddMonths(Number);
                    break;
            }
            return dt;
        }

        private void CheckByTrue()
        {
            lastDoneDateEdit.Enabled = false;
            alarmDaybeforeTextEdit.Enabled = false;
        }

        private void CheckByFasle()
        {
            lastDoneDateEdit.Enabled = true;
            alarmDaybeforeTextEdit.Enabled = true;
        }

        private bool TestJobDescrExits(int id, int jobID)
        {
            foreach (Job j in jobBindingSource.Cast<Job>().ToList())
            {
                if (j.JobDescription_ID == id && j.Job_ID != jobID)
                {
                    return true;
                }
            }
            return false;

        }

        private void sC_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {

            if (job != null)
            {
                try
                {
                    ((Job)gridView12.GetFocusedRow()).ServiceCode = BaseDAL.DB.ServiceCodes.Single(c => c.SC_ID == (int)e.NewValue);
                }
                catch { }
            }
        }

        private void jobBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isJobChanged = true;
        }

        private void cbbTimeUnit_TextChanged(object sender, EventArgs e)
        {
            if (cbbTimeUnit.Text == "Hour(s)")
            {
                CheckByTrue();
            }
            else
            {
                CheckByFasle();
            }
            if (null == job)
                ucLoadJobDescription1.SetValue("", "", "");
        }

        private void jobBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                if (ucLoadJobDescription1.isChanges || ucRichEditControl2.isChange)
                {
                    job.JobDescription = BaseDAL.DB.JobDescriptions.Single(c => c.JobDescription_ID == int.Parse(ucLoadJobDescription1.lbid.Text));
                    ucLoadJobDescription1.isChanges = false;
                    job.Details = ucRichEditControl2.richEditControl1.Text;
                    ucRichEditControl2.isChange = false;
                }

                job = jobBindingSource.Current as Job;

                ucRichEditControl2.richEditControl1.Text = job.Details;
                ucLoadJobDescription1.SetValue(job.JobDescription.CodeJD, job.JobDescription.NameJD, job.JobDescription.JobDescription_ID.ToString());

            }
            catch { }
            LoadDataIntoTabPageJob(xtraTabControl5.SelectedTabPage);
        }

        #endregion

        #region Part  in job

        // Khai báo trạng thái mặc định 
        private Status statusPartJob = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private JobPart jpart;
        //Hiển thị số thứ tự của gridview
        private void gridViewPJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewPJ_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SavePartJobToDatabase();
        }
        private void SavePartJobToDatabase()
        {
            if (TestBeforeAddPartJob())
            {
                if (statusPartJob == Status.Update)
                {
                    jpart = jobPartBindingSource.Current as JobPart;
                    if (XtraMessageBox.Show("Do you want to save change?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        bool result = PartJob_BLL.Update(jpart);
                        if (!result)
                        {
                            XtraMessageBox.Show("Update Unuccessfull!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                            if (objWorkOrder != null)
                            {
                                PartWorkOrder partWorkOrder = new PartWorkOrder();

                                partWorkOrder.Parts_ID = jpart.Parts_ID;
                                partWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                                partWorkOrder.Quantity = jpart.Quantity;
                                partWorkOrder.PartCode = jpart.PartCode;
                                partWorkOrder.PartName = jpart.PartName;
                                PartWorkOrder_BLL.Update(partWorkOrder);
                            }
                            XtraMessageBox.Show("Update Successfull!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }

                    jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(job.Job_ID, true);
                }
                if (statusPartJob == Status.New)
                {
                    bool result = PartJob_BLL.Insert(jpart);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccessly!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                        if (objWorkOrder != null)
                        {
                            PartWorkOrder partWorkOrder = new PartWorkOrder();
                            partWorkOrder.Parts_ID = jpart.Parts_ID;
                            partWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                            partWorkOrder.Quantity = jpart.Quantity;
                            partWorkOrder.PartCode = jpart.PartCode;
                            partWorkOrder.PartName = jpart.PartName;
                            bool rr = PartWorkOrder_BLL.Insert(partWorkOrder);
                        }
                    }
                    statusPartJob = Status.Update;
                }

            }
            else
            {
                XtraMessageBox.Show("Save new job before add record !!!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void txtQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void repositoryItemGridLookUpEdit5_EditValueChanged(object sender, EventArgs e)
        {
            gridView15.PostEditor();
        }

        private void repositoryItemGridLookUpEdit6_EditValueChanged(object sender, EventArgs e)
        {
            gridView15.PostEditor();
        }

        private void DeletePartJob(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                if (jpart != null && PartJob_BLL.isExits(jpart))
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                    if (objWorkOrder != null)
                    {
                        PartWorkOrder partWorkOrder = new PartWorkOrder();
                        partWorkOrder.Parts_ID = jpart.Parts_ID;
                        partWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                        partWorkOrder.Quantity = jpart.Quantity;

                        PartWorkOrder_BLL.Delete(partWorkOrder);
                    }
                    bool result = PartJob_BLL.Delete(jpart);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(job.Job_ID, false);
                }
                else
                {
                    jobPartBindingSource.RemoveCurrent();
                }
            }
            e.Handled = true;
        }

        // Sự kiện nhân phím delete sảy ra
        private void gridViewPJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    if (jpart != null && PartJob_BLL.isExits(jpart))
                    {
                        WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                        if (objWorkOrder != null)
                        {
                            PartWorkOrder partWorkOrder = new PartWorkOrder();
                            partWorkOrder.Parts_ID = jpart.Parts_ID;
                            partWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                            partWorkOrder.Quantity = jpart.Quantity;

                            PartWorkOrder_BLL.Delete(partWorkOrder);
                        }
                        bool result = PartJob_BLL.Delete(jpart);
                        if (!result)
                        {
                            XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(job.Job_ID, false);
                    }
                    else
                    {
                        jobPartBindingSource.RemoveCurrent();
                    }
                }
            }
        }

        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewPJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            statusPartJob = Status.New;

            GridView view = (GridView)sender;
            view.SetRowCellValue(e.RowHandle, colQuantity, 0);
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewPJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (null != job)
            {
                GridView view = (GridView)sender;
                GridColumn PartCode = view.Columns["PartCode"];
                if (null == view.GetRowCellValue(e.RowHandle, colPartCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Please enter the Part ";
                    view.SetColumnError(PartCode, "Part cannot be empty");
                    return;
                }

                if (null == PartInEquipment_BLL.GetDataByNumber(view.GetRowCellDisplayText(view.FocusedRowHandle, colPartCode)))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Please enter the Part ";
                    view.SetColumnError(PartCode, "Part hasn't existed");
                    return;
                }
                
                if (PartJob_BLL.isExits(jpart) && statusPartJob != Status.Update)
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Part has existed. ";
                    view.SetColumnError(PartCode, "Part has existed");
                    return;
                }
            }
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewPJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl2.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    jobPartBindingSource.DataSource = PartJob_BLL.GetDataByJobID(job.Job_ID, false);
                    statusPartJob = Status.Update;
                }
            }

        }

        private bool flag = false;
        // Đặt lại trạng thái update 
        private void gridViewPJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusPartJob = Status.Update;
            }
            GridView view = gridControl3.FocusedView as GridView;
            if (e.Column.FieldName == "PartCode" && flag == false)
            {
                flag = true;
                if (e.Value != null && view.FocusedRowHandle == GridControl.NewItemRowHandle)
                {
                    PartsInEquipment part;
                    part = PartInEquipment_BLL.GetDataByNumber(view.GetRowCellDisplayText(view.FocusedRowHandle, e.Column));

                    if (part != null)
                    {
                        if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
                        {
                            view.AddNewRow();
                        }

                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode3, part.PartCode);
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName3, part.PartName);
                        view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                        jpart.PartsInEquipment = part;
                        jpart.Parts_ID = part.Parts_ID;
                    }
                    else
                    {
                        view.SetColumnError(colPartCode, "Equipment cannot be empty");

                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode3, "");
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName3, "");
                    }
                    flag = false;
                }
            }
        }

        #endregion

        #region Attachment

        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }

        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream fileStream = new System.IO.FileStream
                    (fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                // Writes a block of bytes
                fileStream.Write(byteArray, 0, byteArray.Length);

                // Close file stream
                fileStream.Close();

                return true;
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
            }
            return false;
        }
        private bool isChangedA;
        private void attachmentBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedA = true;
        }
        private void repositoryItemButtonEdit2_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                OpenDocument();
            }
            catch { }
        }


        private void btnUploadFile_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Select one file upload";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {

                string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                FileInfo fileInfo = new FileInfo(fileName);
                long sizeFile = fileInfo.Length / 1000;
                if (sizeFile <= 3000)
                {
                    string extension = Path.GetExtension(fileName);
                    attachment.Extension = extension;
                    byte[] fileByteArray = StreamFile(fileName);
                    // Converts it to Binary
                    // it can be done inside the method as well
                    Binary fileBinary = new Binary(fileByteArray);
                    attachment.ContentFile = fileBinary;
                    GridColumn AttachExtension = gridView18.Columns["Extension"];
                    extension = extension.ToUpper();
                    gridView18.SetRowCellValue(gridView18.FocusedRowHandle, AttachExtension, extension);
                }
                else
                {
                    XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

        }

        // Khai báo trạng thái mặc định 
        private Status statusAttachment = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private Attachment attachment = new Attachment();
        //Hiển thị số thứ tự của gridview
        private void gridViewA_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        LockMouseClickEvent lockMouseClick = new LockMouseClickEvent();
        private void gridViewA_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveAttachmentToDatabase();
        }

        private void SaveAttachmentToDatabase()
        {
            if (TestBeforeAddJob())
            {
                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));


                if (statusAttachment == Status.Update)
                {
                    if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        thread.Start();
                        bool result = Attachment_BLL.Update(attachment);
                        if (!result)
                        {
                            XtraMessageBox.Show("Update Unsuccess !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                    isChangedA = false;

                }

                if (statusAttachment == Status.New)
                {
                    thread.Start();
                    attachment.Equipment_ID = int.Parse(CURRENT_NODE.Name);
                    bool result = Attachment_BLL.Insert(attachment);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusAttachment = Status.Update;
                }

                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));
            }
        }

        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Office 2007 Blue");
            }
        }

        private void DeleteAttachment(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                attachment = attachmentBindingSource.Current as Attachment;
                bool result = Attachment_BLL.Delete(attachment);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                isChangedA = false;
            }
            e.Handled = true;
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewA_KeyDown(object sender, KeyEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                if (e.KeyCode == Keys.Delete)
                {
                    if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        attachment = attachmentBindingSource.Current as Attachment;
                        bool result = Attachment_BLL.Delete(attachment);
                        if (!result)
                        {
                            XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                        isChangedA = false;
                    }
                    e.Handled = true;
                }
            }
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewA_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                statusAttachment = Status.New;
            }
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewA_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (CURRENT_NODE != null && CURRENT_NODE.Name != "0" && CURRENT_NODE.Name != "-1")
            {
                GridView view = (GridView)sender;
                GridColumn AttachName = view.Columns["Name"];
                GridColumn AttachCode = view.Columns["Code"];
                GridColumn AttachContent = view.Columns["ContentFile"];
                if (null == view.GetRowCellValue(e.RowHandle, AttachCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Please enter the Attachment Code. ";
                    view.SetColumnError(AttachCode, "Attachment Code is not empty");
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachContent))
                {
                    e.Valid = false;
                    e.ErrorText = "Please upload one file into table ";
                }
                attachment = attachmentBindingSource.Current as Attachment;
                attachment.Equipment_ID = int.Parse(CURRENT_NODE.Name);
                if (Attachment_BLL.IsExits(attachment))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Attachment Code is exits. ";
                    view.SetColumnError(AttachCode, "Attachment Code is exits");
                }
            }
        }
        private void attachmentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            attachment = attachmentBindingSource.Current as Attachment;
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewA_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {

            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl2.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                    isChangedA = false;
                }
            }
        }
        // Đặt lại trạng thái update 
        private void gridViewA_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusAttachment = Status.Update;
            }
        }

        private void OpenDocument()
        {
            if (gridView18.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                string Address = Application.StartupPath + "\\Attachment\\";
                Directory.CreateDirectory(Address);
                attachment = attachmentBindingSource.Current as Attachment;
                Attachment attach = Attachment_BLL.GetDataById(attachment.Attachments);

                if (null != attach)
                {
                    string fileName = attach.Name + attach.Extension;
                    Address += fileName;
                    if (ByteArrayToFile(Address, attach.ContentFile.ToArray()))
                    {
                        try
                        {
                            Process.Start(Address);
                        }
                        catch
                        {

                        }
                    }
                }
            }
        }
        #endregion

        #region Part

        // Khai báo trạng thái mặc định 
        private Status statusPart = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private PartsInEquipment part = new PartsInEquipment();
        //Hiển thị số thứ tự của gridview
        private void gridViewP_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SavePartEToDatabase();
        }

        private void partsInEquipmentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            part = partsInEquipmentBindingSource.Current as PartsInEquipment;
        }

        private void partsInEquipmentBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedA = true;
        }

        private void SavePartEToDatabase()
        {
            if (TestBeforeAddJob())
            {
                part = partsInEquipmentBindingSource.Current as PartsInEquipment;
                part.IsCheck = false;
                if (statusPart == Status.Update)
                {
                    if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        bool result = PartInEquipment_BLL.Update(part);
                        if (!result)
                        {
                            XtraMessageBox.Show("Update Unsuccess !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                        isChangedA = false;
                    }
                }
                if (statusPart == Status.New)
                {
                    // part.Equipment_ID = int.Parse(CURRENT_NODE.Name);
                    bool result = PartInEquipment_BLL.Insert(part);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusPart = Status.Update;
                }
            }
        }

        private void DeletePart(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                part = partsInEquipmentBindingSource.Current as PartsInEquipment;
                bool result = PartInEquipment_BLL.Delete(part);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                isChangedA = false;
            }
            e.Handled = true;
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (TestBeforeAddJob())
                {
                    if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        part = partsInEquipmentBindingSource.Current as PartsInEquipment;
                        bool result = PartInEquipment_BLL.Delete(part);
                        if (!result)
                        {
                            XtraMessageBox.Show("Can't Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                        isChangedA = false;
                    }
                    e.Handled = true;
                }
            }
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                statusPart = Status.New;
            }
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (CURRENT_NODE != null && CURRENT_NODE.Name != "-1" && CURRENT_NODE.Name != "0")
            {
                GridView view = (GridView)sender;
                GridColumn PartCode = view.Columns[0];
                GridColumn PartName = view.Columns[1];

                if (null == view.GetRowCellValue(e.RowHandle, PartCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Please enter the Part";
                    view.SetColumnError(PartCode, "Part is not empty");
                    view.SetColumnError(PartName, "Part is not empty");
                }

                part = partsInEquipmentBindingSource.Current as PartsInEquipment;
                part.Equipment_ID = int.Parse(CURRENT_NODE.Name);

                if (PartInEquipment_BLL.isExits(part))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Part is exits. ";
                    view.SetColumnError(PartCode, "Part is exits");
                    view.SetColumnError(PartName, "Part is exits");
                }
            }
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl2.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(int.Parse(CURRENT_NODE.Name), isChangedA);
                    isChangedA = false;
                }
            }
        }
        // Đặt lại trạng thái update 
        private void gridViewP_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusPart = Status.Update;
            }
        }

        private void InUse_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void InStock_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void MaxPart_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void MinPart_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        #endregion

        #region Attachment Job

        // Khai báo trạng thái mặc định 
        private Status statusAttachmentJob = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private AttachmentsJob attachmentJob = new AttachmentsJob();
        //Hiển thị số thứ tự của gridview

        private void gridViewAJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private bool isChangedAJ;
        private void attachmentsJobBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedAJ = true;
        }
        private void attachmentsJobBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            attachmentJob = attachmentsJobBindingSource.Current as AttachmentsJob;
        }

        private void btnOpenFileJob_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                OpenDocumentAJ();
            }
            catch { }
        }

        private void btnUploadFileAJ_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Select one file upload";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                FileInfo fileInfo = new FileInfo(fileName);
                long sizeFile = fileInfo.Length / 1000;
                if (sizeFile <= 3000)
                {
                    string extension = Path.GetExtension(fileName);
                    attachmentJob.Extentsion = extension;
                    byte[] fileByteArray = StreamFile(fileName);
                    // Converts it to Binary
                    // it can be done inside the method as well
                    Binary fileBinary = new Binary(fileByteArray);
                    attachmentJob.ContentFile = fileBinary;
                    GridColumn AttachExtension = gridView13.Columns["Extentsion"];
                    extension = extension.ToUpper();
                    gridView13.SetRowCellValue(gridView13.FocusedRowHandle, AttachExtension, extension);
                }
                else
                {
                    XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewAJ_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveAttachmentJobToDatabase();
        }

        private void SaveAttachmentJobToDatabase()
        {
            if (TestBeforeAddPartJob())
            {

                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));

                if (statusAttachmentJob == Status.Update)
                {
                    if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        thread.Start();
                        bool result = AttachmentJob_BLL.Update(attachmentJob);
                        if (!result)
                        {
                            XtraMessageBox.Show("Update Unsuccess !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                            if (objWorkOrder != null)
                            {
                                AttachmentWorkOrder attachWorkOrder = AttachmentWorkOrder_BLL.GetDataByAttachmentJob(attachmentJob.Attachment_ID);
                                attachWorkOrder.Code = attachmentJob.Code;
                                attachWorkOrder.Name = attachmentJob.Name;
                                attachWorkOrder.ContentFile = attachmentJob.ContentFile;
                                attachWorkOrder.Extension = attachmentJob.Extentsion;

                                AttachmentWorkOrder_BLL.Update(attachWorkOrder);
                            }
                        }
                        attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(job.Job_ID, isChangedAJ);
                        isChangedAJ = false;
                    }
                }

                if (statusAttachmentJob == Status.New)
                {
                    thread.Start();
                    attachmentJob.Job_ID = job.Job_ID;
                    bool result = AttachmentJob_BLL.Insert(attachmentJob);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        attachmentJob = AttachmentJob_BLL.GetLastData();
                        WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                        if (objWorkOrder != null)
                        {
                            AttachmentWorkOrder attachWorkOrder = new AttachmentWorkOrder();
                            attachWorkOrder.Code = attachmentJob.Code;
                            attachWorkOrder.Name = attachmentJob.Name;
                            attachWorkOrder.ContentFile = attachmentJob.ContentFile;
                            attachWorkOrder.Extension = attachmentJob.Extentsion;
                            attachWorkOrder.WorkOrder_ID = objWorkOrder.WorkOrder_ID;
                            attachWorkOrder.AttachmentJob_ID = attachmentJob.Attachment_ID;

                            AttachmentWorkOrder_BLL.Insert(attachWorkOrder);
                        }
                    }
                    statusAttachmentJob = Status.Update;
                }

                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));
            }
        }
        private void DeleteAttachmentJob(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                if (attachmentJob != null && AttachmentJob_BLL.IsExitsID(attachmentJob))
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                    if (objWorkOrder != null)
                    {
                        AttachmentWorkOrder_BLL.DeleteByID(attachmentJob.Attachment_ID);
                    }
                    bool result = AttachmentJob_BLL.Delete(attachmentJob);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(job.Job_ID, isChangedAJ);
                    //     isChangedAJ = false;
                }
                else
                {
                    attachmentsJobBindingSource.RemoveCurrent();
                }
            }
            e.Handled = true;

        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewAJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                if (attachmentJob != null && AttachmentJob_BLL.IsExitsID(attachmentJob))
                {
                    WorkOrder objWorkOrder = WorkOrder_BLL.GetWorkOrderByJobID(job.Job_ID);
                    if (objWorkOrder != null)
                    {
                        AttachmentWorkOrder_BLL.DeleteByID(attachmentJob.Attachment_ID);
                    }
                    bool result = AttachmentJob_BLL.Delete(attachmentJob);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(job.Job_ID, isChangedAJ);
                    //     isChangedAJ = false;
                }
                else
                {
                    attachmentsJobBindingSource.RemoveCurrent();
                }
            }
            e.Handled = true;
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewAJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (TestBeforeAddPartJob())
            {
                statusAttachmentJob = Status.New;
            }
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewAJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            try
            {
                if (null != job)
                {
                    GridView view = (GridView)sender;
                    GridColumn AttachName = view.Columns["Name"];
                    GridColumn AttachCode = view.Columns["Code"];
                    GridColumn AttachContent = view.Columns["ContentFile"];

                    if (null == view.GetRowCellValue(e.RowHandle, AttachName))
                    {
                        e.Valid = false;
                        view.FocusedColumn = AttachName;
                        e.ErrorText = "Please enter the Attachment Name. ";
                        view.SetColumnError(AttachName, "Attachment Name is not empty");
                    }

                    if (null == view.GetRowCellValue(e.RowHandle, AttachCode))
                    {
                        e.Valid = false;
                        view.FocusedColumn = AttachCode;
                        e.ErrorText = "Please enter the Attachment Code. ";
                        view.SetColumnError(AttachCode, "Attachment Code is not empty");
                    }

                    if (null == view.GetRowCellValue(e.RowHandle, AttachContent))
                    {
                        e.Valid = false;
                        e.ErrorText = "Please upload one file into table ";
                    }

                    attachmentJob = attachmentsJobBindingSource.Current as AttachmentsJob;
                    attachmentJob.Job_ID = job.Job_ID;
                    if (IsExits(attachmentJob))
                    {
                        e.Valid = false;
                        view.FocusedColumn = AttachCode;
                        e.ErrorText = "Attachment Code is exits. ";
                        view.SetColumnError(AttachCode, "Attachment Code is exits");
                    }
                }
            }
            catch { }
        }

        private bool IsExits(AttachmentsJob attach)
        {
            for (int i = 0; i < attachmentsJobBindingSource.Cast<AttachmentsJob>().ToList().Count - 1; i++)
            {
                AttachmentsJob aj = attachmentsJobBindingSource.Cast<AttachmentsJob>().ToList()[i];
                if (aj.Code == attach.Code)
                {
                    return true;
                }
            }
            return false;
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewAJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {

            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl2.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    attachmentsJobBindingSource.DataSource = AttachmentJob_BLL.GetDataByJobID(job.Job_ID, isChangedAJ);
                    //   isChangedAJ = false;
                }
            }
        }

        // Đặt lại trạng thái update 
        private void gridViewAJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusAttachmentJob = Status.Update;
            }
        }

        private void OpenDocumentAJ()
        {
            if (gridView13.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                string Address = Application.StartupPath + "\\Attachment\\";
                Directory.CreateDirectory(Address);
                if (attachmentJob.Attachment_ID != 0)
                {
                    AttachmentsJob attach = AttachmentJob_BLL.GetDataById(attachmentJob.Attachment_ID);
                    if (null != attach)
                    {
                        string fileName = attach.Name + attach.Extentsion;
                        Address += fileName;
                        if (ByteArrayToFile(Address, attach.ContentFile.ToArray()))
                        {
                            try
                            {
                                Process.Start(Address);
                            }
                            catch
                            {
                                XtraMessageBox.Show("Can't open file", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }

                    }
                }
                else
                {
                    string fileName = attachmentJob.Name + attachmentJob.Extentsion;
                    Address += fileName;
                    if (ByteArrayToFile(Address, attachmentJob.ContentFile.ToArray()))
                    {
                        try
                        {
                            Process.Start(Address);
                        }
                        catch
                        {
                            XtraMessageBox.Show("Can't open file", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
        }

        #endregion

        #region Update Counter
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private Equipment equipment = new Equipment();

        //Hiển thị số thứ tự của gridview
        private void gridViewC_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        // Sự kiện cập nhật dữ liệu xuống databse
        private void gridViewC_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveCounterToDatabase();
        }

        private void SaveCounterToDatabase()
        {
            if (XtraMessageBox.Show("Do you want to save changes", "Infomation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                equipment = equipmentBindingSource.Current as Equipment;

                HistoryCounter counterHistory = new HistoryCounter();
                counterHistory.Counters = equipment.CurrentCounter;
                counterHistory.DateUpdate = equipment.TempDate;
                counterHistory.Equipment_ID = equipment.Equipment_ID;
                bool historyResult = CounterHistory_BLL.Insert(counterHistory);

                int ValueChange = equipment.CurrentCounter.Value - equipment.OldCounter.Value;
                WorkOrder_BLL.UpdateCounterOfJob(equipment.Equipment_ID, ValueChange);

                equipment.OldCounter = equipment.CurrentCounter;
                equipment.IsCounter = true;

                bool result = Equipment_BLL.UpdateCounter(equipment);
                XtraMessageBox.Show("Save success !", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                equipmentBindingSource.DataSource = Equipment_BLL.GetDataById(int.Parse(CURRENT_NODE.Name));
            }
        }

        // Sự kiện click vào thành Navigator
        private void datnaviMainC_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.EndEdit:
                    SaveCounterToDatabase();
                    break;
                case NavigatorButtonType.CancelEdit:

                    break;
            }
        }
        private void txtSetvalue_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void gridViewC_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column == colCurrentCounter)
            {
                GridView view = sender as GridView;
                GridColumn dateCol = view.Columns[4];
                view.SetFocusedRowCellValue(dateCol, DateTime.Today.ToString());
            }
        }
        #endregion

        #region History

        private void gridViewH_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        #endregion

        private void gridView24_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private bool isPJChanged;
        private void jobPartBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isPJChanged = true;
        }
        private void repositoryItemGridLookUpEdit6_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (null == e.NewValue)
                ((JobPart)gridView15.GetFocusedRow()).PartsInEquipment = null;
            else
                ((JobPart)gridView15.GetFocusedRow()).PartsInEquipment = BaseDAL.DB.PartsInEquipments.Single(c => c.Parts_ID == (int)e.NewValue);
        }

        private void gridView24_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView24_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;

            Point pt = view.GridControl.PointToClient(Control.MousePosition);

            DoRowDoubleClick(view, pt);
        }
        WorkOrder workOrder;
        private void DoRowDoubleClick(GridView view, Point pt)
        {
            GridHitInfo info = view.CalcHitInfo(pt);

            if (info.InRow || info.InRowCell)
            {
                if (info.RowHandle != GridControl.NewItemRowHandle)
                {
                    workOrder = workOrderBindingSource.Current as WorkOrder;
                    List<WorkOrder> woList = new List<WorkOrder>();
                    woList.Add(workOrder);
                    frmWorkOrderDeatails workOrderDetails = new frmWorkOrderDeatails(woList, objMain);
                    workOrderDetails.MdiParent = objMain;
                    workOrderDetails.Show();
                }
            }
        }

        private void requisitionWorkToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (CURRENT_NODE != null && CURRENT_NODE.Name != "0" && CURRENT_NODE.Name != "-1")
            {
                frmRequistionWork requireWork = new frmRequistionWork(objMain, int.Parse(CURRENT_NODE.Name));
                requireWork.ShowDialog();
            }
        }
        private void employee_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (null == e.NewValue)
                ((Job)gridView12.GetFocusedRow()).Employee = null;
            else
                ((Job)gridView12.GetFocusedRow()).Employee = BaseDAL.DB.Employees.Single(c => c.Employee_ID == (int)e.NewValue);
        }

        private void gluMaker_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (null == e.NewValue)
                ((PartsInEquipment)gridView16.GetFocusedRow()).Maker = null;
            else
                ((PartsInEquipment)gridView16.GetFocusedRow()).Maker = BaseDAL.DB.Makers.Single(c => c.Maker_ID == (int)e.NewValue);
        }

        private void gluVendor_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (null == e.NewValue)
                ((PartsInEquipment)gridView16.GetFocusedRow()).Vendor = null;
            else
                ((PartsInEquipment)gridView16.GetFocusedRow()).Vendor = BaseDAL.DB.Vendors.Single(c => c.Vendor_ID == (int)e.NewValue);
        }
        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            NewComponent();
            txtNumber.Focus();
        }

        private void btnSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SaveAll();
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CURRENT_NODE != null)
            {
                if (XtraMessageBox.Show("Do you want to delete this Equipment ?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    if (Equipment_BLL.TestBeforeDeleteComponentFinal(int.Parse(tvEquipment.SelectedNode.Name)))
                    {
                        if (ListEquipmentUpdated.Count > 0)
                        {
                            XtraMessageBox.Show("The data has changed ! Please save and refresh hierachy equipment", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        else
                        {
                            DeleteNode();
                            CURRENT_NODE = tvEquipment.SelectedNode;
                            ShowValueWhenClicked(CURRENT_NODE);
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
            }
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshDisplay();
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XtraMessageBox.Show("This function building", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // PrintDocument();
        }
        private void gridView12_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void gridControl4_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        if (TestBeforeAddJob())
                        {
                            DeletePart(e);
                        }
                        break;
                }
            }
        }

        private void gridControl12_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        if (TestBeforeAddJob())
                        {
                            DeleteAttachment(e);
                        }
                        break;
                }
            }
        }

        private void gridView29_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void gridControl3_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddPartJob())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        DeletePartJob(e);
                        break;
                }
            }
        }

        private void gridControl17_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.Remove:
                    if (TestBeforeAddPartJob())
                    {
                        DeleteAttachmentJob(e);
                    }
                    break;
            }
        }

        private void freodicFrequencyTextEdit_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void timeDoneTextEdit_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void alarmDaybeforeTextEdit_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }
        private void gridView29_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;

            Point pt = view.GridControl.PointToClient(Control.MousePosition);

            DoRowDoubleClickHistory(view, pt);
        }
        private void DoRowDoubleClickHistory(GridView view, Point pt)
        {
            GridHitInfo info = view.CalcHitInfo(pt);

            if (info.InRow || info.InRowCell)
            {
                if (info.RowHandle != GridControl.NewItemRowHandle)
                {
                    List<History> histories = History_BLL.GetAllByEquipment(int.Parse(CURRENT_NODE.Name));
                    frmHistoryDetail historyDetail = new frmHistoryDetail(histories);
                    historyDetail.MdiParent = objMain;
                    historyDetail.Show();
                }
            }
        }
        private void btnLoadPart_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            frmGridPart gridPart = new frmGridPart();
            gridPart.ShowDialog();
            GridView view = gridView15 as GridView;
            if (gridPart.PartsInEquipment != null)
            {
                if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
                {
                    view.AddNewRow();
                }
                view.SetRowCellValue(view.FocusedRowHandle, colPartCode3, gridPart.PartsInEquipment.PartCode);
                view.SetRowCellValue(view.FocusedRowHandle,colPartName3, gridPart.PartsInEquipment.PartName);
                view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                jpart.PartsInEquipment = gridPart.PartsInEquipment;
            }
        }

        private void jobPartBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            jpart = jobPartBindingSource.Current as JobPart;
            if (null != jpart)
                jpart.Job = job;
        }

        private void gridView15_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            if (!view.IsNewItemRow(view.FocusedRowHandle) && view.FocusedColumn != colQuantity)
                e.Cancel = true;
        }

        private void gluStatus_EditValueChanging(object sender, ChangingEventArgs e)
        {
            
        }
    }
}